TFRSI & RSI Analog Dial [CHE]  TFRSI & RSI Analog Dial    — Interactive analog visualization for TFRSI or RSI with gradient zones, radial markers, and a trailing hand pointer.
  Summary 
This indicator renders an interactive analog dial for either TFRSI or standard RSI, providing a visual gauge with gradient-filled zones for oversold, neutral, and overbought regions. The hand pointer tracks the current value, with optional trailing dots at recent positions to show momentum direction. Radial lines mark key thresholds, and a digital readout displays the exact value. This design enhances readability over linear plots by leveraging familiar clock-like intuition, reducing cognitive load during quick scans. Signals are robust due to clamping to safe bounds and mode-specific scaling, ensuring consistent display across different volatility regimes.
  Motivation: Why this design? 
Traditional linear RSI or momentum indicators often feel abstract, especially in fast-paced screening where users scan multiple assets. Sharp swings can make thresholds hard to gauge at a glance, leading to missed nuances in overbought or oversold conditions. This dial addresses that by mapping values to a curved scale with color gradients, making extremes visually pop while the hand's trail hints at recent path without cluttering the chart. The dual-mode support allows seamless switching between advanced momentum (TFRSI) and classic RSI, fitting diverse strategies without reloading scripts.
  What’s different vs. standard approaches? 
- Baseline reference: Diverges from linear plotlines like the built-in RSI oscillator, which stacks values vertically and relies on horizontal lines for thresholds.
- Architecture differences:
  - Curved projection with perspective tilt for depth illusion, using polyline arcs instead of straight plots.
  - Mode-aware clamping and scaling to handle TFRSI's extended range versus RSI's standard bounds.
  - Persistent trail array for hand history, capped at three points to avoid performance drag.
  - Gradient segmentation for smooth zone transitions, rendered via multiple thin polylines.
- Practical effect: Charts show a compact, rotatable dial that fits in pane corners, with colors intuitively signaling bias (lime for buy zones, red for sell). The trail adds qualitative flow without numerical overload, helping spot divergences faster than static bars.
  How it works (technical) 
The indicator first computes the selected metric: for TFRSI, it processes price accelerations through a multi-step filter involving differencing, exponential damping, and normalization to a centered scale; for RSI, it uses the standard gain-loss ratio over the specified period. The value is then clamped between mode-specific minimum and maximum bounds to prevent display overflow.
This clamped value drives the hand angle on a 300-degree arc, projected from a 3D-like model rotated for perspective. Arcs for zones are built as segmented polylines, with colors interpolated linearly across the gradient. Key levels are drawn as radial lines from inner to outer radius, colored by zone. The trail maintains up to three prior angles in an array, updated only on confirmed bars to avoid repainting, and rendered as sized dots fading from small to large.
Initialization seeds filter states to zero on first bar, with persistent variables holding smoothing history. Data flows from price to metric computation, clamping, angle mapping, and projection—all executed globally on the last bar for redraw efficiency.
  Parameter Guide 
Mode — Switches between TFRSI (extended momentum gauge) and RSI (classic oscillator); affects bounds, zones, and labels. Default: "TFRSI". Trade-offs: TFRSI adds sensitivity to accelerations but may amplify noise; RSI is more stable for trend confirmation.
Dial Size — Sets radius in pixels, scaling all elements proportionally. Default: 200. Bounds: 50–500. Tips: Larger for detailed views, smaller for multi-pane layouts; auto-scales hand length to match.
Dial Vertical Offset — Shifts entire dial up/down in pixels. Default: 0. Bounds: -200–200. Trade-offs: Negative pulls toward price action; positive spaces below—use to avoid overlap.
Camera Angle — Tilts view from top-down (0) to side (90) for 3D effect. Default: 45. Bounds: 0–90. Tips: Steeper angles emphasize depth but compress horizontally; flat for precision.
Resolution — Polygon sides for smooth arcs. Default: 64. Bounds: 4–64. Trade-offs: Higher reduces jaggedness but increases draw calls—balance with pane zoom.
TFRSI Hand Length — Base pointer length at 200px dial, auto-scaled. Default: 170. Bounds: 10–200. Tips: Longer for emphasis in large dials; shorter avoids edge clipping.
Show TFRSI Hand — Toggles pointer visibility. Default: true. Trade-offs: Off for clean zones only; on for value tracking.
Show Hand Trail Dots — Displays 3 fading dots at recent tips. Default: true. Trade-offs: Adds motion context but may clutter static views—disable in alerts.
TFRSI Hand Color — Pointer hue, used for trail dots too. Default: 7E57C2. Tips: Match strategy theme; gradients auto-blend to zones.
Dial Base Color — Arc outline/fill tint. Default: blue. Trade-offs: Opaque for contrast; transparent blends with background.
Neutral Color (50) — Mid-zone shade. Default: gray. Tips: Neutral tones reduce bias in balanced markets.
Oversold Color — Low-zone fill. Default: lime. Trade-offs: Bright for alerts; muted for subtlety.
Overbought Color — High-zone fill. Default: red. Trade-offs: As above—pair with hand blending.
Label Size — Text scaling for thresholds. Default: "normal". Options: tiny/small/normal/large/huge. Tips: Smaller for dense charts; larger for presentations.
Digital TFRSI Size — Readout font. Default: "large". Options: as above. Trade-offs: Balances visibility without dominating dial.
Digital Vertical Offset — Readout position shift. Default: -50. Bounds: -200–200. Tips: Negative centers above dial; adjust for multi-indicators.
TFRSI Length — Core lookback for accelerations. Default: 6. Min: 1. Trade-offs: Shorter heightens reactivity, risks whipsaws; longer smooths extremes.
TFRSI Trigger Length — Final smoothing passes. Default: 2. Min: 1. Tips: Increase for fewer false crosses; decrease for quicker pivots.
RSI Length — Period for gain-loss averaging. Default: 14. Min: 1. Trade-offs: Classic 14 balances; shorter for scalps, longer for swings.
  Reading & Interpretation 
The dial arcs sweep from overbought (right, red) through neutral (top, gray) to oversold (left, lime), with the hand pointing to the current value—clockwise for rising, counterclockwise for falling. Trail dots grow larger toward the present, colored to match hand zones, indicating recent direction without numbers. Threshold lines thicken at center (50) for quick zeroing; labels confirm levels. Digital readout below shows precise value prefixed by mode. Hand color gradients from neutral to extremes signal building pressure verbally: deepening red warns of potential pullbacks, brightening lime suggests bounces.
  Practical Workflows & Combinations 
Trend following: Enter long when hand crosses above 50 from oversold trail; confirm with higher highs in price structure. Filter shorts below 50 in downtrends using volume spikes.
Exits/Stops: Trail stops to recent dot positions in overbought; tighten on red gradients exceeding thresholds. Conservative: Exit at neutral; aggressive: Hold to extremes if trail aligns with momentum.
Multi-asset/Multi-TF: Defaults suit forex/stocks on 1H–4H; for crypto, shorten lengths by 20% for volatility. Stack with HTF security calls (e.g., daily mode on 15m chart) for confluence—watch for alignment across dials.
  Behavior, Constraints & Performance 
Closed-bar updates ensure no repainting; live bars show provisional hand/trail, confirmed on close. No security or HTF calls, so zero lookahead bias. Resources: Caps at 500 lines/labels/polylines, rebuilds only on last bar; max_bars_back=2000 handles history without lag. Known limits: Trail may stutter in flat markets; gradients approximate smooth fills via segments, visible at low resolution.
  Sensible Defaults & Quick Tuning 
Start with TFRSI mode, length=6, trigger=2 for responsive momentum on daily charts. Too choppy? Bump trigger to 4 for stability. Lagging entries? Drop length to 4, watch for overreactions. For RSI trend filter, set length=21; combine with MA cross for entries when dial nears 30/70.
  What this indicator is—and isn’t 
This is a visualization layer for momentum gauges, aiding quick bias assessment and threshold spotting. Pair it with price action, volume, and risk rules for decisions. It’s not a standalone signal generator or predictive tool—values reflect past data, prone to whipsaws in ranging conditions.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.  
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.  
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.  
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.  
 Best regards and happy trading  
Chervolino
Polyline
Pivot Regime Anchored VWAP [CHE]  Pivot Regime Anchored VWAP   — Detects body-based pivot regimes to classify swing highs and lows, anchoring volume-weighted average price lines directly at higher highs and lower lows for adaptive reference levels.
  Summary 
This indicator identifies shifts between top and bottom regimes through breakouts in candle body highs and lows, labeling swing points as higher highs, lower highs, lower lows, or higher lows. It then draws anchored volume-weighted average price lines starting from the most recent higher high and lower low, providing dynamic support and resistance that evolve with volume flow. These anchored lines differ from standard volume-weighted averages by resetting only at confirmed swing extremes, reducing noise in ranging markets while highlighting momentum shifts in trends.
  Motivation: Why this design? 
Traders often struggle with static reference lines that fail to adapt to changing market structures, leading to false breaks in volatile conditions or missed continuations in trends. By anchoring volume-weighted average price calculations to body pivot regimes—specifically at higher highs for resistance and lower lows for support—this design creates reference levels tied directly to price structure extremes. This approach addresses the problem of generic moving averages lagging behind swing confirmations, offering a more context-aware tool for intraday or swing trading.
  What’s different vs. standard approaches? 
- Baseline reference: Traditional volume-weighted average price indicators compute a running total from session start or fixed periods, often ignoring price structure.
- Architecture differences:
  - Regime detection via body breakout logic switches between high and low focus dynamically.
  - Anchoring limited to confirmed higher highs and lower lows, with historical recalculation for accurate line drawing.
  - Polyline rendering rebuilds only on the last bar to manage performance.
- Practical effect: Charts show fewer, more meaningful lines that start at swing points, making it easier to spot confluences with structure breaks rather than cluttered overlays from continuous calculations.
  How it works (technical) 
The indicator first calculates the maximum and minimum of each candle's open and close to define body highs and lows. It then scans a lookback window for the highest body high and lowest body low. A top regime triggers when the body high from the lookback period exceeds the window's highest, and a bottom regime when the body low falls below the window's lowest. These regime shifts confirm pivots only when crossing from one state to the other.
For top pivots, it compares the new body high against the previous swing high: if greater, it marks a higher high and anchors a new line; otherwise, a lower high. The same logic applies inversely for bottom pivots. Anchored lines use cumulative price-volume products and volumes from the anchor bar onward, subtracting prior cumulatives to isolate the segment. On pivot confirmation, it loops backward from the current bar to the anchor, computing and storing points for the line. New points append as bars advance, ensuring the line reflects ongoing volume weighting.
Initialization uses persistent variables to track the last swing values and anchor bars, starting with neutral states. Data flows from regime detection to pivot classification, then to anchoring and point accumulation, with lines rendered globally on the final bar.
  Parameter Guide 
Pivot Length — Controls the lookback window for detecting body breakouts, influencing pivot frequency and sensitivity to recent action. Shorter values catch more pivots in choppy conditions; longer smooths for major swings. Default: 30 (bars). Trade-offs/Tips: Min 1; for intraday, try 10–20 to reduce lag but watch for noise; on daily, 50+ for stability.
Show Pivot Labels — Toggles display of text markers at swing points, aiding quick identification of higher highs, lower highs, lower lows, or higher lows. Default: true. Trade-offs/Tips: Disable in multi-indicator setups to declutter; useful for backtesting structure.
HH Color — Sets the line and label color for higher high anchored lines, distinguishing resistance levels. Default: Red (solid). Trade-offs/Tips: Choose contrasting hues for dark/light themes; pair with opacity for fills if added later.
LL Color — Sets the line and label color for lower low anchored lines, distinguishing support levels. Default: Lime (solid). Trade-offs/Tips: As above; green shades work well for bullish contexts without overpowering candles.
  Reading & Interpretation 
Higher high labels and red lines indicate potential resistance zones where volume weighting begins at a new swing top, suggesting sellers may defend prior highs. Lower low labels and lime lines mark support from a fresh swing bottom, with the line's slope reflecting buyer commitment via volume. Lower highs or higher lows appear as labels without new anchors, signaling possible range-bound action. Line proximity to price shows overextension; crosses may hint at regime shifts, but confirm with volume spikes.
  Practical Workflows & Combinations 
- Trend following: Enter longs above a rising lower low anchored line after higher low confirmation; filter with rising higher highs for uptrends. Use line breaks as trailing stops.
- Exits/Stops: In downtrends, exit shorts below a higher high line; set aggressive stops above it for scalps, conservative below for swings. Pair with momentum oscillators for divergence.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 1H–4H; on crypto 15M, shorten length to 15. Scale colors for dark themes; combine with higher timeframe anchors for confluence.
  Behavior, Constraints & Performance 
Closed-bar logic ensures pivots confirm after the lookback period, with no repainting on historical bars—live bars may adjust until regime shift. No higher timeframe calls, so minimal repaint risk beyond standard delays. Resources include a 2000-bar history limit, label/polyline caps at 200/50, and loops for historical point filling (up to current bar count from anchor, typically under 500 iterations). Known limits: In extreme gaps or low-volume periods, anchors may skew; lines absent until first pivots.
  Sensible Defaults & Quick Tuning 
Start with the 30-bar length for balanced pivot detection across most assets. For too-frequent pivots in ranges, increase to 50 for fewer signals. If lines lag in trends, reduce to 20 and enable labels for visual cues. In low-volatility assets, widen color contrasts; test on 100-bar history to verify stability.
  What this indicator is—and isn’t 
This is a structure-aware visualization layer for anchoring volume-weighted references at swing extremes, enhancing manual analysis of regimes and levels. It is not a standalone signal generator or predictive model—always integrate with broader context like order flow or news. Use alongside risk management and position sizing, not as isolated buy/sell triggers.
Many thanks to LuxAlgo for the original script "McDonald's Pattern  ". The implementation for body pivots instead of wicks uses a = max(open, close), b = min(open, close) and then highest(a, length) / lowest(b, length). This filters noise from the wicks and detects breakouts over/under bodies. Unusual and targeted, super innovative.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino
Anchored VWAP Polyline [CHE]  Anchored VWAP Polyline   — Anchored VWAP drawn as a polyline from a user-defined bar count with last-bar updates and optional labels
  Summary 
This indicator renders an anchored Volume-Weighted Average Price as a continuous polyline starting from a user-selected anchor point a specified number of bars back. It accumulates price multiplied by volume only from the anchor forward and resets cleanly when the anchor moves. Drawing is object-based (polyline and labels) and updated on the most recent bar only, which reduces flicker and avoids excessive redraws. Optional labels mark the anchor and, conditionally, a delta label when the current close is below the historical close at the anchor offset.
  Motivation: Why this design? 
Anchored VWAP is often used to track fair value after a specific event such as a swing, breakout, or session start. Traditional plot-based lines can repaint during live updates or incur overhead when frequently redrawn. This implementation focuses on explicit state management, last-bar rendering, and object recycling so the line stays stable while remaining responsive when the anchor changes. The design emphasizes deterministic updates and simple session gating from the anchor.
  What’s different vs. standard approaches? 
 Baseline: Classic VWAP lines plotted from session open or full history.
 Architecture differences:
   Anchor defined by a fixed bar offset rather than session or day boundaries.
   Object-centric drawing via `polyline` with an array of `chart.point` objects.
   Last-bar update pattern with deletion and replacement of the polyline to apply all points cleanly.
   Conditional labels: an anchor marker and an optional delta label only when the current close is below the historical close at the offset.
 Practical effect: You get a visually continuous anchored VWAP that resets when the anchor shifts and remains clean on chart refreshes. The labels act as lightweight diagnostics without clutter.
  How it works (technical) 
 The anchor index is computed as the latest bar index minus the user-defined bar count.
 A session flag turns true from the anchor forward; prior bars are excluded.
 Two persistent accumulators track the running sum of price multiplied by volume and the running sum of volume; they reset when the session flag turns from false to true.
 The anchored VWAP is the running sum divided by the running volume whenever both are valid and the volume is not zero.
 Points are appended to an array only when the anchored VWAP is valid. On the most recent bar, any existing polyline is deleted and replaced with a new one built from the point array.
 Labels are refreshed on the most recent bar:
   A yellow warning label appears when there are not enough bars to compute the reference values.
   The anchor label marks the anchor bar.
   The delta label appears only when the current close is below the close at the anchor offset; otherwise it is suppressed.
 No higher-timeframe requests are used; repaint is limited to normal live-bar behavior.
  Parameter Guide 
Bars back — Sets the anchor offset in bars; default two hundred thirty-three; minimum one. Larger values extend the anchored period and increase stability but respond more slowly to regime changes.
Labels — Toggles all labels; default enabled. Disable to keep the chart clean when using multiple instances.
  Reading & Interpretation 
 The polyline represents the anchored VWAP from the chosen anchor to the current bar. Price above the line suggests strength relative to the anchored baseline; price below suggests weakness.
 The anchor label shows where the accumulation starts.
 The delta label appears only when today’s close is below the historical close at the offset; it provides a quick context for negative drift relative to that reference.
 A yellow message at the current bar indicates the chart does not have enough history to compute the reference comparison yet.
  Practical Workflows & Combinations 
 Trend following: Anchor after a breakout bar or a swing confirmation. Use the anchored VWAP as dynamic support or resistance; look for clean retests and holds for continuation.
 Mean reversion: Anchor at a local extreme and watch for approaches back toward the line; require structure confirmation to avoid early entries.
 Session or event studies: Re-set the anchor around earnings, macro releases, or session opens by adjusting the bar offset.
 Combinations: Pair with structure tools such as swing highs and lows, or with volatility measures to filter chop. The labels can be disabled when combining multiple instances to maintain chart clarity.
  Behavior, Constraints & Performance 
 Repaint and confirmation: The line is updated on the most recent bar only; historical values do not rely on future bars. Normal live-bar movement applies until the bar closes.
 No higher timeframe: There is no `security` call; repaint paths related to higher-timeframe lookahead do not apply here.
 Resources: Uses one polyline object that is rebuilt on the most recent bar, plus two labels when conditions are met. `max_bars_back` is two thousand. Arrays store points from the anchor forward; extremely long anchors or very long charts increase memory usage.
 Known limits: With very thin volume, the VWAP can be unavailable for some bars. Very large anchors reduce responsiveness. Labels use ATR for vertical placement; extreme gaps can place them close to extremes.
  Sensible Defaults & Quick Tuning 
 Starting point: Bars back two hundred thirty-three with Labels enabled works well on many assets and timeframes.
 Too noisy around the line: Increase Bars back to extend the accumulation window.
 Too sluggish after regime changes: Decrease Bars back to focus on a shorter anchored period.
 Chart clutter with multiple instances: Disable Labels while keeping the polyline visible.
  What this indicator is—and isn’t 
This is a visualization of an anchored VWAP with optional diagnostics. It is not a full trading system and does not include entries, exits, or position management. Use it alongside clear market structure, risk controls, and a plan for trade management. It does not predict future prices.
 Inputs with defaults 
 Bars back: two hundred thirty-three bars, minimum one.
 Labels: enabled or disabled toggle, default enabled.
Pine version: v6
Overlay: true
Primary outputs: one polyline, optional labels (anchor, conditional delta, and a warning when insufficient bars).
Metrics and functions: volume, ATR for label offset, object drawing via polyline and chart points, last-bar update pattern.
Special techniques: session gating from the anchor, persistent state, object recycling, explicit guards against unavailable values and zero volume.
Compatibility and assets: Designed for standard candlestick or bar charts across liquid assets and common timeframes.
Diagnostics: Yellow warning label when history is insufficient.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino 
PseudoPlotLibrary   "PseudoPlot" 
PseudoPlot: behave like plot and fill using polyline
This library enables line plotting by polyline like plot() and fill().
The core of polyline() is array of chart.point array, polyline() is called in its method.
Moreover, plotarea() makes a box in main chart, plotting data within the box is enabled.
It works so slowy to manage array of chart.point, so limit the target to visible area of the chart.
Due to polyline specifications, na and expression can not be used for colors.
1. pseudoplot
pseudoplot() behaves like plot().
 
//use plot()
plot(close)
//use pseudoplot()
pseudoplot(close)
 
Pseudoplot has label. Label is enabled when title argument is set.
In the example bellow, "close value" label is shown with line.
The label is shown at right of the line when recent bar is visible.
It is shown at 15% from the left of visible area when recent bar is not visible.
Just set "" if you don't need label.
 
//use plot()
plot(close,"close value")
//use pseudoplot
pseudoplot(close, "close value")
 
Arguments are designed in an order as similar as possible to plot.
 
plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display, format, precision, force_overlay) → plot
pseudoplot(series, title, ,linecolor ,linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) → pseudo_plot
 
2. pseudofill
pseudofill() behaves like fill().
The label is shown(text only) at right of the line when recent bar is visible.
It is shown at 10% from the left of visible area when recent bar is not visible.
Just set "" if you don't need label.
 
//use plot() and fill()
p1=plot(open)
p2=plot(close)
fill(p1,p2)
//use pseudofill()
pseudofill(open,close)
 
Arguments are designed in an order as similar as possible to fill.
 
fill(hline1, hline2, color, title, editable, fillgaps, display) → void
pseudofill(series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) → pseudo_plot
 
3. plotarea and its methods
plotarea() makes a box in main chart. You can set the box position to top or bottom, and
the box height in percentage of the range of visible high and low prices.
x-coordinate of the box is from chart.left_visible_bar_time to chart.right_visible_bar_time,
y-coordinate is highest and lowest price of visible bars.
pseudoplot() and pseudofill() work as method of plotarea(box).
Usage is almost same as the function version, just set min and max value, y-coodinate is remapped automatically.
hline() is also available. The y-coordinate of hline is specified as a percentage from the bottom.
plotarea() and its associated methods are overlay=true as default.
Depending on the drawing order of the objects, plot may become invisible, so the bgcolor of plotarea should be na or tranceparent.
 
//1. make a plotarea
// bgcolor should be na or transparent color.
area=plotarea("bottom",30,"plotarea",bgcolor=na)
//2. plot in a plotarea
//(min=0, max=100 is omitted as it is the default.)
area.pseudoplot(ta.rsi(close,14))
//3. draw hlines
area.hline(30,linestyle="dotted",linewidth=2)
area.hline(70,linestyle="dotted",linewidth=2)
 
4. Data structure and sub methods
Array management is most imporant part of using polyline.
I don't know the proper way to handle array, so it is managed by array and array as intermediate data.
(type xy_arrays to manage bar_time and price as independent arrays.)
method cparray() pack arrays to array, when array includes both chart.left_visible_bar_time and chart.right_visible_bar.time.
Calling polyline is implemented as methods of array of chart.point.
Method creates polyline object if array is not empty.
 
method polyline(linecolor, linewidth, linestyle, overlay) → series polyline
method polyline_fill(fillcolor, linecolor, linewidth, linestyle, overlay) → series polyline
 
Also calling label is implemented as methods of array of chart.point.
Method creates label ofject if array is not empty.
Label is located at right edge of the chart when recent bar is visible, located at left side when recent bar is invisible.
 
label(title, labelbg, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) → series label
label_for_fill(title, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) → series label
 
 visible_xyInit(series) 
  make arrays of visible x(bar_time) and y(price/value).
  Parameters:
     series (float) : (float)		series variable
  Returns: (xy_arrays)
 method remap(this, bottom, top, min, max) 
  Namespace types: xy_arrays
  Parameters:
     this (xy_arrays) 
     bottom (float) : (float)		bottom price to ajust.
     top (float) : (float)		top price to ajust.
     min (float) : (float)		min of src value.
     max (float) : (float)		max of src value.
  Returns: (xy_arrays)
 method polyline(this, linecolor, linewidth, linestyle, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     linecolor (color) : (color) 	color of polyline.
     linewidth (int) : (int) 		width of polyline.
     linestyle (string) : (string)	linestyle of polyline. default is line.style_solid("solid"), others line.style_dashed("dashed"), line.style_dotted("dotted").
     overlay (bool) : (bool)		force_overlay of polyline. default is false.
  Returns: (polyline)
 method polyline_fill(this, fillcolor, linecolor, linewidth, linestyle, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     fillcolor (color) 
     linecolor (color) : (color) 	color of polyline.
     linewidth (int) : (int) 		width of polyline.
     linestyle (string) : (string)	linestyle of polyline. default is line.style_solid("solid"), others line.style_dashed("dashed"), line.style_dotted("dotted").
     overlay (bool) : (bool)		force_overlay of polyline. default is false.
  Returns: (polyline)
 method label(this, title, labelbg, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     title (string) : (string) 	label text.
     labelbg (color) : (color) 	color of label bg.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     overlay (bool) : (bool)		force_overlay of label. default is false.
  Returns: (label)
 method label_for_fill(this, title, labeltext, labelsize, format, shorttitle, xpos_from_left, overlay) 
  Namespace types: array
  Parameters:
     this (array) 
     title (string) : (string) 	label text.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 10%.
     overlay (bool) : (bool)		force_overlay of label. default is false.
  Returns: (label)
 pseudoplot(series, title, linecolor, linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) 
  polyline like plot with label
  Parameters:
     series (float) : (float)		series variable to plot.
     title (string) : (string)	title if need label. default value is ""(disable label).
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labelbg (color) : (color)		color of label bg.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label text.
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudo_plot)
 method pseudoplot(this, series, title, linecolor, linewidth, linestyle, labelbg, labeltext, labelsize, shorttitle, format, xpos_from_left, min, max, overlay) 
  Namespace types: series box
  Parameters:
     this (box) 
     series (float) : (float)		series variable to plot.
     title (string) : (string)	title if need label. default value is ""(disable label).
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labelbg (color) : (color)		color of label bg.
     labeltext (color) : (color)		color of label text.
     labelsize (int) : (int)		size of label text.
     shorttitle (string) : (string)	another label text for recent bar is not visible.
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     min (float) 
     max (float) 
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudo_plot)
 pseudofill(series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, overlay) 
  fill by polyline
  Parameters:
     series1 (float) : (float)		series variable to plot.
     series2 (float) : (float)		series variable to plot.
     fillcolor (color) : (color)		color of fill.
     title (string) 
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labeltext (color) 
     labelsize (int) 
     shorttitle (string) 
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudoplot)
 method pseudofill(this, series1, series2, fillcolor, title, linecolor, linewidth, linestyle, labeltext, labelsize, shorttitle, format, xpos_from_left, min, max, overlay) 
  Namespace types: series box
  Parameters:
     this (box) 
     series1 (float) : (float)		series variable to plot.
     series2 (float) : (float)		series variable to plot.
     fillcolor (color) : (color)		color of fill.
     title (string) 
     linecolor (color) : (color)		color of line.
     linewidth (int) : (int)		width of line.
     linestyle (string) : (string)	style of plotting line. default is "solid", others "dashed", "dotted".
     labeltext (color) 
     labelsize (int) 
     shorttitle (string) 
     format (string) : (string)	textformat of label. default is text.format_none("none"). others text.format_bold("bold"), text.format_italic("italic"), text.format_bold+text.format_italic("bold+italic").
     xpos_from_left (int) : (int)	another label x-position(percentage from left of chart width), when recent bar is not visible. default is 15%.
     min (float) 
     max (float) 
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (pseudo_plot)
 plotarea(pos, height, title, bordercolor, borderwidth, bgcolor, textsize, textcolor, format, overlay) 
  subplot area in main chart
  Parameters:
     pos (string) : (string)	position of subplot area, bottom or top.
     height (int) : (float)		percentage of visible chart heght.
     title (string) : (string)	text of area box.
     bordercolor (color) : (color)	color of border.
     borderwidth (int) : (int)		width of border.
     bgcolor (color) : (string)	color of area bg.
     textsize (int) 
     textcolor (color) 
     format (string) 
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (box)
 method hline(this, ypos_from_bottom, linecolor, linestyle, linewidth, overlay) 
  Namespace types: series box
  Parameters:
     this (box) 
     ypos_from_bottom (float) : (float)		percentage of box height from the bottom of box.(bottom is 0%, top is 100%).
     linecolor (color) : (color)		color of line.
     linestyle (string) : (string)	style of line.
     linewidth (int) : (int)		width of line.
     overlay (bool) : (bool)		force_overlay of polyline and label.
  Returns: (line)
 pseudo_plot 
  polyline and label.
  Fields:
     p (series polyline) 
     l (series label) 
 xy_arrays 
  x(bartime) and y(price or value) arrays.
  Fields:
     t (array) 
     p (array)
Market Stats Panel [Daveatt]█ Introduction 
I've created a script that brings TradingView's watchlist stats panel functionality directly to your charts. This isn't just another performance indicator - it's a pixel-perfect (kidding) recreation of TradingView's  native stats panel. 
 Important Notes 
You might need to adjust manually the scaling the firs time you're using this script to display nicely all the elements.
 █ Core Features 
 Performance Metrics 
The panel displays key performance metrics (1W, 1M, 3M, 6M, YTD, 1Y) in real-time, with color-coded boxes (green for positive, red for negative) for instant performance assessment.
 Display Modes 
Switch seamlessly between absolute prices and percentage returns, making it easy to compare assets across different price scales.
 Absolute mode 
  
 Percent mode 
  
 Historical Comparison 
View year-over-year performance with color-coded lines, allowing for quick historical pattern recognition and analysis.
 Data Structure Innovation 
Let's talk about one of the most interesting challenges I faced. PineScript has this quirky limitation where request.security() can only return 127 tuples at most. £To work around this, I implemented a dual-request system. The first request handles indices 0-63, while the second one takes care of indices 64-127. 
This approach lets us maintain extensive historical data without compromising script stability. 
And here's the cool part: if you need to handle even more years of historical data, you can simply extend this pattern by adding more request.security() calls. 
Each additional call can fetch another batch of monthly open prices and timestamps, following the same structure I've used. 
Think of it as building with LEGO blocks - you can keep adding more pieces to extend your historical reach.
 Flexible Date Range 
Unlike many scripts that box you into specific timeframes, I've designed this one to be completely flexible with your date selection. You can set any start year, any end year, and the script will dynamically scale everything to match. The visual presentation automatically adjusts to whatever range you choose, ensuring your data is always displayed optimally.
 █ Customization Options 
 Visual Settings 
The panel's visual elements are highly customizable. You can adjust the panel width to perfectly fit your workspace, fine-tune the line thickness to match your preferences, and enjoy the pre-defined year color scheme that makes tracking historical performance intuitive and visually appealing.
 Box Dimensions 
Every aspect of the performance boxes can be tailored to your needs. Adjust their height and width, fine-tune the spacing between them, and position the entire panel exactly where you want it on your chart. The goal is to make this tool feel like it's truly yours.
 █ Technical Challenges Solved 
 Polyline Precision 
Creating precise polylines was perhaps the most demanding aspect of this project. 
The challenge was ensuring accurate positioning across both time and price axes, while handling percentage mode scaling with precision. 
The script constantly updates the current year's data in real-time, seamlessly integrating new information as it comes in.
 Axis Management 
Getting the axes right was like solving a complex puzzle. The Y-axis needed to scale dynamically whether you're viewing absolute prices or percentages. 
The X-axis required careful month labeling that stays clean and readable regardless of your selected timeframe. 
Everything needed to align perfectly while maintaining proper spacing in all conditions.
 █ Final Notes 
This tool transforms complex market data into clear, actionable insights. Whether you're day trading or analyzing long-term trends, it provides the information you need to make informed decisions. And remember, while we can't predict the future, we can certainly be better prepared for it with the right tools at hand.
A word of warning though - seeing those red numbers in a beautifully formatted panel doesn't make them any less painful! 😉
---
Happy Trading! May your charts be green and your stops be far away!
Daveatt
Patrick [TFO]This Patrick indicator was made for the 1 year anniversary of my Spongebob indicator, which was an experiment in using the polyline features of Pine Script to draw complex subjects. This indicator was made with the same methodology, with some helper functions to make things a bit easier on myself. It's sole purpose is to display a picture of Patrick Star on your chart, particularly the "I have $3" meme.
  
The initial Spongebob indicator included more than 1300 lines of code, as there were several more shapes to account for compared to Patrick, however it was done rather inefficiently. I essentially used an anchor point for each "layer" or shape (eye, nose, mouth, etc.), and drew from that point. This resulted in a ton of trial and error as I had to be very careful about the anchor points for each and every layer, and then draw around that point. In this indicator, however, I gave myself a frame to work with by specifying fixed bounds that you'll see in the code: LEFT, RIGHT, TOP, and BOTTOM.
 
var y_size = 4
atr = ta.atr(50)
LEFT = bar_index + 10
RIGHT = LEFT + 200
TOP = open + atr * y_size
BOTTOM = open - atr * y_size
 
You may notice that the top and bottom scale with the atr, or Average True Range to account for varying price fluctuations on different assets.
With these limits established, I could write some simple functions to translate my coordinates, using a range of 0-100 to describe how far the X coordinates should be from left to right, where left is 0 and right is 100; and likewise how far the Y coordinates should be from bottom to top, where bottom is 0 and top is 100.
 
X(float P) =>
    result = LEFT + math.floor((RIGHT - LEFT)*P/100)
Y(float P) =>
    result = BOTTOM + (TOP - BOTTOM)*P/100
 
With these functions, I could then start drawing points much simpler, with respect to the overall frame of the picture. If I wanted a point in the dead center of the frame, I would choose X(50), Y(50) for example.
At this point, the process just became tediously drawing each layer of my reference picture, including but not limited to Patrick's body, arm, mouth, eyes, eyebrows, etc. I've attached the reference picture here (left), without the text enabled.
  
As tedious as this was to create, it was done much more efficiently than Spongebob, and the ideas used here will make it much easier to draw more complex subjects in the future.
Speedometer RevisitedSpeedometer Revisited is a new way to draw custom metric speedometers and is intended to be a utility for other coders to use.
@rumpypumpydumpy originally introduced the Speedometer Toolkit in version 4 of Pine Script. Since then, Pine Script has been updated to version 5, introducing some amazing new features such as polylines and chart.points. This indicator is an example of what can be done with these newer features.
The indicator starts off with a handful of functions that will be used to create the drawings. Notes are left throughout the code explaining what each line of the functions does. My goal was to make these functions user-friendly and somewhat easy to understand. I then demonstrate two examples: one speedometer with five segments and another with three.
The  first example  demonstrates how to visually represent the analysts' ratings for a stock using the built-in syminfo.recommendations. The speedometer is divided into five segments, each representing a different level of analyst recommendation: strong sell, sell, hold, buy, and strong buy.
Each segment is drawn using a polyline from the createSeg function, with colors assigned as follows: 
 
 Red for 'Strong Sell' 
 Maroon for 'Sell'
 Yellow for 'Hold'
 Green for 'Buy'
 Lime for 'Strong Buy'
 
The script identifies the maximum value among the analyst ratings, calculates the midpoint of the corresponding segment, and draws a needle pointing to this midpoint.
The  second example  employs the speedometer design to display market sentiment through the put-call ratio. The put-call ratio is a gauge of investor sentiment, where values above 1 indicate a bearish sentiment (more puts being bought relative to calls), and values below 1 suggest a bullish outlook (more calls being bought relative to puts).
The speedometer is divided into three segments, reflecting different ranges of the put-call ratio: 
 
 Red for a ratio greater than 1 (bearish sentiment) 
 Yellow for a ratio between 0.8 and 1 (neutral to bearish sentiment) 
 Lime for a ratio less than 0.8 (bullish sentiment)
 
Depending on the value of the put-call ratio, the script calculates which segment the current value falls into and determines the appropriate segment number. The script calculates the midpoint of the selected segment and draws a needle pointing to this value.
Both examples show how the speedometer can be used as a visual indicator of certain market conditions, helping traders quickly recognize trends and adjust their strategies accordingly.
A big thanks to @rumpypumpydumpy for his original Speedometer Toolbox. I hope this take on it can be useful for other coders. 
DeleteArrayType█ OVERVIEW
Here are common functions usually delete drawing once array of drawing is recall.
Method is used as in pine script version 5 instead of custom function.
It is an upgrade from  DeleteArrayObject , which may not support overload parameter in future.
Library   "DeleteArrayType" 
TODO: Delete array type especially for drawings
 method deleteLabel(id) 
  TODO: Delete array
  Namespace types: array
  Parameters:
     id (array) 
  Returns: TODO: label.delete()
 method deleteLine(id) 
  TODO: Delete array
  Namespace types: array
  Parameters:
     id (array) 
  Returns: TODO: line.delete()
 method deleteLineFill(id) 
  TODO: Delete array
  Namespace types: array
  Parameters:
     id (array) 
  Returns: TODO: linefill.delete()
 method deletePolyLine(id) 
  TODO: Delete array
  Namespace types: array
  Parameters:
     id (array) 
  Returns: TODO: polyline.delete()
 method deleteBox(id) 
  TODO: Delete array
  Namespace types: array
  Parameters:
     id (array) 
  Returns: TODO: box.delete()
 method deleteTable(id) 
  TODO: Delete array
  Namespace types: array
  Parameters:
     id (array) 
  Returns: TODO: table.delete()
Polyline PlusThis library introduces the `PolylinePlus` type, which is an enhanced version of the built-in PineScript `polyline`. It enables two features that are absent from the built-in type:
1. Developers can now efficiently add or remove points from the polyline. In contrast, the built-in `polyline` type is immutable, requiring developers to create a new instance of the polyline to make changes, which is cumbersome and incurs a significant performance penalty.
2. Each `PolylinePlus` instance can theoretically hold up to ~1M points, surpassing the built-in `polyline` type's limit of 10K points, as long as it does not exceed the memory limit of the PineScript runtime.
Internally, each `PolylinePlus` instance utilizes an array of `line`s and an array of `polyline`s. The `line`s array serves as a buffer to store lines formed by recently added points. When the buffer reaches its capacity, it flushes the contents and converts the lines into polylines. These polylines are expected to undergo fewer updates. This approach is similiar to the concept of "Buffered I/O" in file and network systems. By connecting the underlying lines and polylines, this library achieves an enhanced polyline that is dynamic, efficient, and capable of surpassing the maximum number of points imposed by the built-in polyline.
🔵  API 
Step 1: Import this library
 
import algotraderdev/polylineplus/1 as pp
// remember to check the latest version of this library and replace the 1 above.
 
Step 2: Initialize the `PolylinePlus` type.
 
var p = pp.PolylinePlus.new()
 
There are a few optional params that developers can specify in the constructor to modify the behavior and appearance of the polyline instance.
 
var p = pp.PolylinePlus.new(
  // If true, the drawing will also connect the first point to the last point, resulting in a closed polyline.
  closed = false,
  // Determines the field of the chart.point objects that the polyline will use for its x coordinates. Either xloc.bar_index (default), or xloc.bar_time.
  xloc = xloc.bar_index,
  // Color of the polyline. Default is blue.
  line_color = color.blue,
  // Style of the polyline. Default is line.style_solid.
  line_style = line.style_solid,
  // Width of the polyline. Default is 1.
  line_width = 1,
  // The maximum number of points that each built-in `polyline` instance can contain.
  // NOTE: this is not to be confused with the maximum of points that each `PolylinePlus` instance can contain.
  max_points_per_builtin_polyline = 10000,
  // The number of lines to keep in the buffer. If more points are to be added while the buffer is full, then all the lines in the buffer will be flushed into the poylines. 
  // The higher the number, the less frequent we'll need to // flush the buffer, and thus lead to better performance.
  // NOTE: the maximum total number of lines per chart allowed by PineScript is 500. But given there might be other places where the indicator or strategy are drawing lines outside this polyline context, the default value is 50 to be safe.
  lines_bffer_size = 50)
 
Step 3: Push / Pop Points
 
// Push a single point
p.push_point(chart.point.now())
// Push multiple points
chart.point  points = array.from(p1, p2, p3) // Where p1, p2, p3 are all chart.point type.
p.push_points(points)
// Pop point
p.pop_point()
// Resets all the points in the polyline.
p.set_points(points)
// Deletes the polyline.
p.delete()
 
🔵  Benchmark 
Below is a simple benchmark comparing the performance between `PolylinePlus` and the native `polyline` type for incrementally adding 10K points to a polyline.
 
import algotraderdev/polylineplus/2 as pp
var t1 = 0
var t2 = 0
if bar_index < 10000
    int start = timenow
    var p = pp.PolylinePlus.new(xloc = xloc.bar_time, closed = true)
    p.push_point(chart.point.now())
    t1 += timenow - start
    start := timenow
    var polyline pl = na
    var points = array.new()
    points.push(chart.point.now())
    if not na(pl)
        pl.delete()
    pl := polyline.new(points)
    t2 += timenow - start
if barstate.islast
    log.info('{0} {1}', t1, t2)
 
For this benchmark, `PolylinePlus` took ~300ms, whereas the native `polyline` type took ~6000ms.
We can also fine-tune the parameters for `PolylinePlus` to have a larger buffer size for `line`s and a smaller buffer for `polyline`s.
 
var p = pp.PolylinePlus.new(xloc = xloc.bar_time, closed = true, lines_buffer_size = 500, max_points_per_builtin_polyline = 1000)
 
With the above optimization, it only took `PolylinePlus` ~80ms to process the same 10K points, which is ~75x the performance compared to the native `polyline`.
RSI Radar Multi Time FrameHello All! 
First of all many Thanks to Tradingview and Pine Team for developing Pine Language all the time! Now we have a new feature and it's called  Polylines  and I developed  RSI Radar Multi Time Frame . This script is an example and experimental work, you can use it as you wish.
The scripts gets RSI values from 6 different time frames, it doesn't matter the time frame you choose is higher/lower or chart time frame. it means that the script can get RSI values from higher or lower time frames than chart time frame.
It's designed to show RSI Radar all the time on the chart even if you zoom in/out or scroll left/right.
You can set OB/OS or RSI line colors. Also RSI polyline is shown as Curved/Hexagon optionally.
Some screenshots here:
Doesn't matter if you zoom out, it can show RSI radar in the visible area:
Another example:
You can change the colors, or see the RSI as Hexagon:
Time frames from seconds to 1Day in this example while chart time frame is any ( 30mins here )
 Enjoy! 









